<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class FriendController extends Controller
{
    public function getAdd(){
        return view('admin/friend/add');
    }
    public function postInsert(Request $request){
         $this->validate($request, [
            'name' => 'required',
            'url' => 'required',
        ],[
            'name.required' => '商家名称必填',
            'url.required' => '商家地址必填'
        ]);
         $arr['f_name'] = $request -> input('name');
         $arr['f_url'] = $request -> input('url');
         if($request -> hasFile('pic')){
            $temp_name = rand(11111,999999).time();
            $hz = $request -> file('pic') -> getClientOriginalExtension();
            $name = $temp_name.'.'.$hz;
            $arr['f_pic'] = $name;
            $request -> file('pic') -> move('./public/fimage/',$name);
         }else{
            return back() -> withInput() -> with('error','请选择友情商标');
         }
        $res = DB::table('shop_friend') -> insert($arr);
        if($res){
            return redirect('/admin/friend/index') -> with('success','添加成功');
        }else{
            return back() -> withInput() -> with('error','添加失败');
        }
    }
    public function getIndex(){
        $data = DB::table('shop_friend') -> get();
        return view('admin/friend/index',['data'=>$data]);
    }
    public function getDelete($id){

        $res = DB::table('shop_friend') -> where('f_id',$id) -> delete();
        
        if($res){
            return redirect('/admin/friend/index') -> with('success','删除成功');
        }else{
            return back() -> withInput() -> with('error','删除失败');
        }
    }
    public function getEdit($id){
        $data = DB::table('shop_friend') -> where('f_id',$id) -> first();
        return view('admin/friend/edit',['data'=>$data]);
    }
    public function postUpdate($id,Request $request){
        $this->validate($request, [
            'name' => 'required',
            'url' => 'required',
        ],[
            'name.required' => '商家名称必填',
            'url.required' => '商家地址必填'
        ]);
        $arr['f_name'] = $request -> input('name');
        $arr['f_url'] = $request -> input('url');
        if($request -> hasFile('pic')){
            $temp_name = rand(111111,999999).time();
            $hz = $request -> file('pic') -> getClientOriginalExtension();
            $name = $temp_name.'.'.$hz;
            $arr['f_pic'] = $name;
            $request -> file('pic') -> move('./public/fimage/',$name);

        }
        $res = DB::table('shop_friend') -> where('f_id',$id) -> update($arr);
        if($res){
            return redirect('/admin/friend/index') -> with('success','修改成功');
        }else{
            return back() -> withInput() -> with('error','修改失败');
        }
    }
}
